<template>
    <!-- 活动表单信息控件 -->
    <el-card shadow="never" class="detail-content">
        <div class="content">
            <el-scrollbar
                id="activityInfoForm"
                ref="activityScrollBarRef"
                class="activity-info-form"
                @scroll="handleScrollChange">
                <activityForm ref="activityFormRef" v-model="formParams" :is-short-link="isShortLink"></activityForm>
            </el-scrollbar>
            <div class="activity-phone">
                <activityPhone v-model="formParams" v-model:phone-preview-index="phonePreviewIndex" />
            </div>
        </div>
    </el-card>
    <!-- 控制步骤的按钮 -->
    <div class="detail-footer">
        <el-button plain @click="onCancel">{{ route.query.type == 'look' ? '返回' : '取消' }}</el-button>
        <el-button v-if="route.query.type != 'look'" type="primary" @click="onSave">保存</el-button>
    </div>
</template>
<script setup lang="ts">
import activityForm from './components/activityForm.vue';
import activityPhone from './components/activityPhone.vue';

import { ref, reactive, markRaw, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { ElMessage, ElMessageBox } from 'element-plus';
import { WarningFilled } from '@element-plus/icons-vue';
import { IFormParams } from './interface';
import { cloneDeep, isPlainObject } from 'lodash';

import {
    punchCardCreate,
    punchCardEdit,
    punchCardDetail,
    openSessionList,
    getMpBaseInfo
} from '@/api/smartMarketing/community/communityCheckIn';

const route = useRoute();
const router = useRouter();

const activityFormRef = ref<any>(null);

const phonePreviewIndex = ref(0);

const isShortLink = ref<boolean>(false);

const defaultFormParams: IFormParams = {
    activity_name: '',
    period_type: 1,
    activity_time: [],
    description: '',
    clock_password: '',
    points_num: null,
    clock_time_range: [[]],
    clock_groupchat: 1,
    groupchat_list: [],
    auto_send_switch: 2,
    // auto_send_time_range: [[], [], []],
    welcome_info: {
        welcome_text: `发送##打卡口令##，即可获得以下奖励：\n每日进行打卡，可获得 N 积分\n打卡时间：2023-12-1 至 2023-12-31 的 10:00-12:00`
    }
};

const formParams = reactive<IFormParams>(defaultFormParams);

const handleScrollChange = (val: { scrollTop: number }) => {
    try {
        const activityInfoForm: any = document.querySelector('#activityInfoForm');
        const clockInContent = document.querySelector('#clockInContent');
        const welcomeMaterialContent: any = document.querySelector('#welcomeMaterialContent');
        const clockInRect: any = clockInContent?.getClientRects()[0];
        const welcomeRect: any = welcomeMaterialContent?.getClientRects()[0];
        const scrollViewRect: any = activityInfoForm?.querySelector('.el-scrollbar__view')?.getClientRects()[0];
        // 优先判断是否滚动到了底部
        if (val.scrollTop + activityInfoForm?.clientHeight > scrollViewRect?.height) {
            phonePreviewIndex.value = 1;
            return;
        }
        /**
         * @description DOM_TOP px 是一个安全的距离。dom移动至这个距离时做切换体验回稍微好点
         */
        const DOM_TOP = 220;
        // 依次查找第一个距离顶部为px的dom元素。1、活动，2、话术
        const index = [clockInRect?.top, welcomeRect?.top].findIndex(item => item >= DOM_TOP);
        // phonePreviewIndex 这个变量在activity-phone组件判断了欢迎语组件的索引
        phonePreviewIndex.value = index;
    } catch {
        // 一旦报错，就到第一个
        phonePreviewIndex.value = 0;
    }
};

const onCheck = async () => {
    const text2 = `确定要修改此活动信息吗？修改后历史数据不会变更，新产生的数据将按照新规则执行`;
    if (formParams.clock_groupchat == 1 && route.query.type == 'edit') {
        await ElMessageBox.confirm(text2, '提示', {
            customClass: 'community-checkin-msg-box-confirm',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            icon: markRaw(WarningFilled)
        });
        return;
    }
    if (formParams.clock_groupchat == 1) return;
    const params = {
        groupchat_ids: formParams.groupchat_list.map(el => el.id)
    };
    //
    const res = await openSessionList(params);
    const list = res.filter((el: any) => el.is_open_session_archive != 1 || el.is_delete == 1);
    const text = `你所选择的${formParams.groupchat_list.length}个群聊中，有${list.length}个群聊未开启会话存档或已解散，系统将自动为你取消选择`;
    const text3 = `1、确定要修改此活动信息吗？修改后历史数据不会变更，新产生的数据将按照新规则执行<br/>
                   2、你所选择的${formParams.groupchat_list.length}个群聊中，有${list.length}个群聊未开启会话存档或已解散，系统将自动为你取消选择`;
    let str = '';
    if (route.query.type == 'new' && list.length) {
        str = text;
    }
    if (route.query.type == 'edit') {
        str = text2;
    }
    if (route.query.type == 'edit' && list.length) {
        str = text3;
    }
    if (!str) return;
    await ElMessageBox.confirm(str, '提示', {
        customClass: 'community-checkin-msg-box-confirm',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        icon: markRaw(WarningFilled)
    });
    formParams.groupchat_list = formParams.groupchat_list.filter((el: any) => list.every(i => i.id != el.id));
    return false;
};

/**
 * 判断是否是短链
 */
const onInitShortLink = async () => {
    const res = await getMpBaseInfo({ media_type: 11 });
    const isLink: boolean = res.is_ec_category == 1;
    if (route.query.type == 'new' && isLink) {
        formParams.welcome_info.welcome_text = `${formParams.welcome_info.welcome_text}\n可点击以下链接查询\n##打卡查询短链##`;
    }
    isShortLink.value = isLink;
};

/**
 * 取消
 */
const onCancel = async () => {
    const type = route.query.type;
    const text = type === 'edit' ? '编辑' : '新建';
    ['new', 'edit'].includes(type) &&
        (await ElMessageBox.confirm(`确定要放弃${text}此活动吗？`, '提示', {
            customClass: 'community-checkin-msg-box-confirm',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            icon: markRaw(WarningFilled)
        }));
    router.back();
};

/**
 * 保存
 */
const onSave = async () => {
    try {
        await activityFormRef.value.validate();
    } catch (err: any) {
        const [[errMessage]]: any = Object.values(err);
        ElMessage.warning({
            grouping: true,
            message: errMessage?.message,
            repeatNum: 1
        });
        return;
    }
    await onCheck();
    const params = cloneDeep(formParams);
    params.groupchat_list = params.groupchat_list.map(el => el.id);
    const defaultWelCome = {
        link_title: '快来查看你的打卡结果吧！',
        link_url: '',
        link_decs: '打开查看您的社群打卡记录和打卡奖励',
        link_share_image: 'https://static.scrm.keyid.cn/assets/images/web-pc/default-mini-app.jpg',
        is_default_del: 1
    };
    params.welcome_info.welcome_local_link = params.welcome_info.welcome_local_link.filter(
        el => el.is_default_del != 1
    );
    params.welcome_info.welcome_local_link.push(defaultWelCome);
    if (params.clock_groupchat == 1) {
        params.groupchat_list = [];
    }
    // console.log(params, 'params');
    if (route.query.type == 'new') {
        onNewSave(params);
        return;
    }
    if (route.query.type == 'edit') {
        onEditSave(params);
        return;
    }
};

/**
 * 新建
 */
const onNewSave = async val => {
    await punchCardCreate(val);
    ElMessage.success('创建成功');
    router.back();
};

/**
 * 编辑
 */

const onEditSave = async val => {
    await punchCardEdit(val);
    ElMessage.success('编辑成功');
    router.back();
};

/**
 * 详情
 */
const onLookDetail = async () => {
    const params = { activity_id: route.query.id };
    const res = await punchCardDetail(params);
    // 设置欢迎语的是否是默认的字段，为了禁止删除
    const setDefaultWelcome = (item: any, suffix: string) => {
        // 非默认不处理
        if (item.is_default_del !== 1) {
            return;
        }
        // 截取活动分享链接标题
        if (item.link_title?.endsWith(suffix)) {
            res.welcome_info[suffix] = item.link_url; // 这里是为了改bug，回显时要把对应的link_url带上到欢迎语里。
            item.link_title = item.link_title.substring(0, item.link_title.length - suffix.length);
            return true;
        }
    };
    /** 根据默认的后缀最排序，同时处理是否是默认的字段 */
    const sortWelcomeByDefaultSuffix = (
        welcomeArray: Array<any>,
        suffix: string,
        selctFun: (item: any) => boolean | undefined = (item: any) => setDefaultWelcome(item, suffix)
    ) => {
        // 先查找两个标题，然后放到第一个
        const index = welcomeArray.findIndex(selctFun);
        if (index >= 0) {
            const [welcomeItem] = welcomeArray.splice(index, 1);
            welcomeArray.unshift(welcomeItem);
        }
    };

    if (isPlainObject(res.welcome_info)) {
        ['_punch_card_welcome_suffix'].forEach(item =>
            // 查找对应的，然后放到第一个
            sortWelcomeByDefaultSuffix(res.welcome_info.welcome_material, item)
        );
    }
    // 默认欢迎语做个截取操作, 这个操作放在前端操作，目的是为了顺便做个排序--end。
    activityFormRef.value?.setWelcomeInfo(res.welcome_info);
    Object.assign(formParams, res);
};

onMounted(() => {
    const type = route.query.type;
    onInitShortLink();
    ['look', 'edit'].includes(type) && onLookDetail();
});
</script>
<style lang="scss" scoped>
.detail-content {
    height: calc(100vh - 207px);
    margin-bottom: 16px;

    :deep(.el-card__body) {
        height: 100%;
        padding: 0;
    }

    .content {
        display: flex;
        overflow-x: auto;
        overflow-y: hidden;
        height: 100%;
    }

    .activity-info-form {
        overflow-y: auto;
        width: 70%;
        min-width: 620px;
    }

    .activity-phone {
        display: flex;
        overflow: auto;
        align-items: flex-start;
        flex: 1;
        justify-content: center;
        box-sizing: border-box;
        min-width: 420px;
        border-left: 1px solid #eaeaea;
    }
}

.detail-footer {
    text-align: center;
    margin: 0 -16px -16px;
    padding: 16px 24px;
    border-radius: 0;
    border: none;
    border-top: 1px solid #e4e7ed;
    background-color: #fff;
}
</style>
<style lang="scss">
.community-checkin-msg-box-confirm {
    width: 400px;

    .el-message-box__content {
        padding: 0;
    }

    .el-message-box__container {
        margin: 42px 25px 44px;
        display: flex;
        justify-content: center;

        // align-items: center;
        .el-icon {
            position: relative;
            top: 0;
            transform: translateY(0);

            --el-messagebox-color: #faad14;
        }
    }

    .el-message-box__message {
        padding: 0 0 0 8px;
    }

    .el-button--primary {
        background-color: var(--el-button-bg-color) !important;
    }
}
</style>
